package com.sec.android.app.myfiles.facade.cmd;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.ConfirmDeleteDialog;
import com.sec.android.app.myfiles.dialog.GmsDeleteResultDialog;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileRecord;
import com.sec.android.app.myfiles.module.local.category.CategoryFileRecord;
import com.sec.android.app.myfiles.module.search.SearchFragment;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.operation.FileOperationArgs;
import com.sec.android.app.myfiles.operation.FileOperationFragment;
import com.sec.android.app.myfiles.operation.FileOperationFragment.PostOperation;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import java.util.ArrayList;

public class DeleteRecordCmd extends SimpleCommand implements PostOperation {
    Context mContext;
    AbsMyFilesFragment mFragment;
    int mRecordsType;
    static OperationProgress sProgress;
    private boolean mIsDeleteAll = false;

    public enum OperationProgress {
        SHOW_CONFIRM_POPUP,
        SHOW_SINGLE_CONFIRM_POPUP,
        SHOW_FOLDER_TREE_CONFIRM_POPUP,
        SHOW_OPTIMIZE_STORAGE_DELETE_CONFIRM_POPUP,
        DO_OPERATE
    }

    @Override
    public void execute(INotification notification) {
        Object[] params = (Object[]) notification.getBody();
        mContext = (Context) params[0];
        mFragment = (AbsMyFilesFragment) params[1];
        mRecordsType = FileUtils.ITEM_TYPE.NONE;
        @SuppressWarnings("unchecked")
        ArrayList<FileRecord> recordList = (ArrayList<FileRecord>) params[2];
        OperationProgress progress = (OperationProgress) params[3];
        if (mFragment != null && recordList != null && !recordList.isEmpty()) {
            mIsDeleteAll = mFragment.getTotalFileCount() == recordList.size();
            switch (progress) {
                case SHOW_CONFIRM_POPUP:
                case SHOW_OPTIMIZE_STORAGE_DELETE_CONFIRM_POPUP:
                    sProgress = progress;
                    showDeleteConfirmDialog(progress, mFragment, recordList);
                    break;

                case DO_OPERATE:
                    doDeleteOperate(mContext, mFragment, recordList);
                    break;

                case SHOW_SINGLE_CONFIRM_POPUP:
                case SHOW_FOLDER_TREE_CONFIRM_POPUP:
                    sProgress = progress;
                    showSingleDeleteConfirmDialog(mFragment, recordList.get(0));
                    break;
            }
        }
    }

    private void doDeleteOperate(Context context, AbsMyFilesFragment fragment, ArrayList<FileRecord> recordList) {
        fragment.setDeleteItemEffect();
        mRecordsType = FileUtils.getRecordType(recordList);
        FileOperationArgs args = new FileOperationArgs();
        args.mProcessId = fragment.getProcessId();
        args.mSrcList = recordList;
        args.mFragment = fragment;
        if (sProgress == OperationProgress.SHOW_FOLDER_TREE_CONFIRM_POPUP) {
            args.mDeleteType = OperationProgress.SHOW_FOLDER_TREE_CONFIRM_POPUP;
            for (FileRecord item : recordList) {
                if (item != null) {
                    args.mDst = item;
                }
            }
        }

        FileOperationFragment fg = FileOperationFragment.createInstance(context, fragment, fragment.getFragmentManager(),
                FileOperator.Operation.DELETE, args, this);

        /*** Gate Message **/
        /*
        if (SemGateConfig.isGateEnabled()) {
            for (FileRecord record : recordList) {
                if (record != null) {
                    if (record.isImageFileType()) {
                        android.util.Log.i("GATE", "<GATE-M>PICTURE_DELETED</GATE-M>");
                    } else if (record.isVideoFileType()) {
                        android.util.Log.i("GATE", "<GATE-M>VIDEO_DELETED</GATE-M>");
                    }
                }
            }
        }
        */

        fg.show();
    }

    private void showDeleteConfirmDialog(OperationProgress progress, AbsMyFilesFragment fragment,
                                         ArrayList<FileRecord> recordList) {
        ConfirmDeleteDialog.Builder builder = new ConfirmDeleteDialog.Builder();
        if (progress == OperationProgress.SHOW_OPTIMIZE_STORAGE_DELETE_CONFIRM_POPUP) {
            builder.setTitle(R.string.delete_from_internal_storage);
            builder.setMessage(R.string.optimize_storage_delete_confirm_message);
        } else {
            mRecordsType = FileUtils.getRecordType(recordList);
            switch (mRecordsType) {
                case FileUtils.ITEM_TYPE.FILE:
                    builder.setPluralsMessage(isSamSungCloudDrive(recordList.get(0)) ? R.plurals.n_file_delete_from_samsung_cloud : R.plurals.delete_file_num);
                    break;
                case FileUtils.ITEM_TYPE.FOLDER:
                    builder.setPluralsMessage(isSamSungCloudDrive(recordList.get(0)) ? R.plurals.n_folder_delete_from_samsung_cloud : R.plurals.delete_folder_num);
                    break;
                case FileUtils.ITEM_TYPE.SHORTCUT:
                    builder.setPluralsMessage(R.plurals.delete_shortcut_num);
                    break;
                case FileUtils.ITEM_TYPE.CATEGORY_FOLDER:
                    int targetChildCount = getTargetChildCount(recordList);
                    builder.setTargetChildCount(targetChildCount);
                    builder.setPluralsMessage(getTargetChildMessage(recordList.size(), targetChildCount));
                    break;
                default:
                    builder.setPluralsMessage(isSamSungCloudDrive(recordList.get(0)) ? R.plurals.n_item_delete_from_samsung_cloud : R.plurals.delete_item_num);
                    break;
            }
        }
        builder.setTargetCount(recordList.size());
        builder.setConfirmCode(progress.ordinal());
        ConfirmDeleteDialog confirmDialog = builder.build();
        confirmDialog.setTargetFragment(fragment, R.id.menu_delete);

        if (fragment != null && fragment.getFragmentManager() != null) {
            FragmentTransaction ft = fragment.getFragmentManager().beginTransaction();
            Fragment prev = fragment.getFragmentManager().findFragmentByTag("confirm_delete");
            if (prev != null) {
                ft.remove(prev);
            }
            if (ft != null) {
                ft.add(confirmDialog, "confirm_delete");
                ft.commitAllowingStateLoss();
            }
        }
    }

    private int getTargetChildMessage(int targetCnt, int targetChildCnt) {
        int ret = 0;
        if (targetCnt == 1) {
            ret = R.plurals.n_delete_folder_and_files_in_it;
        } else if (targetCnt > 1 && targetChildCnt > 1) {
            ret = R.plurals.n_delete_folders_and_files_in_it;
        }
        return ret;
    }

    private static boolean isSamSungCloudDrive(FileRecord record) {
        boolean ret = false;
        if (record != null) {
            ret = record.getStorageType() == FileRecord.StorageType.Cloud &&
                    ((CloudFileRecord) record).getCloudType() == FileRecord.CloudType.SamsungDrive;
        }
        return ret;
    }

    private void showSingleDeleteConfirmDialog(Fragment fragment, FileRecord record) {
        if (record != null) {
            ConfirmDeleteDialog.Builder builder = new ConfirmDeleteDialog.Builder();

            builder.setTargetPath(record.getFullPath());
            builder.setTargetCount(1);

            if (record.isDirectory()) {
                if (record.getStorageType() == FileRecord.StorageType.Category) {
                    builder.setPluralsMessage(getTargetChildMessage(1, getTargetChildCount(record)));
                } else {
                    builder.setPluralsMessage(isSamSungCloudDrive(record) ? R.plurals.n_folder_delete_from_samsung_cloud : R.plurals.delete_folder_num);
                }
            } else {
                builder.setPluralsMessage(isSamSungCloudDrive(record) ? R.plurals.n_file_delete_from_samsung_cloud : R.plurals.delete_file_num);
            }

            if (record.getStorageType() == FileRecord.StorageType.Cloud) {
                CloudFileRecord cloudRecord = (CloudFileRecord) record;
                builder.setIsCloud(true, cloudRecord.getDeviceId(), cloudRecord.getParentId(), cloudRecord.getFileId());
            } else {
                builder.setIsCloud(false, 0, null, null);
                if (record instanceof CategoryFileRecord) {
                    builder.setTargetCategoryPath(record.getPath() + "/" + record.getName());
                    builder.setTargetCategoryBucketId(((CategoryFileRecord) record).getBucketId());
                    builder.setTargetChildCount(getTargetChildCount(record));
                }
            }

            ConfirmDeleteDialog confirmDialog = builder.build();
            confirmDialog.setTargetFragment(fragment, R.id.menu_delete);

            FragmentTransaction ft = fragment.getFragmentManager().beginTransaction();
            ft.add(confirmDialog, "confirm_delete");
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onResult(FileOperator.Operation opType, boolean bRet, Bundle extras) {
        if (!bRet || mFragment instanceof SearchFragment) {
            mFragment.finishActionMode();
        }

        if (AppFeatures.isTabletUIMode()) {
            if ((mRecordsType & FileUtils.ITEM_TYPE.FOLDER) != 0) {
                UiUtils.sendLocalBroadcastIntent(mContext, AppConstants.MYFILES_ACTION_FOLDER_DELETED, -1);
            }
        }
        showResultDialog(bRet, extras);
    }

    private void showResultDialog(boolean result, Bundle extras) {
        if (result) {
            NavigationInfo navigationInfo = mFragment.getNavigationInfo();
            if (navigationInfo != null) {
                if (navigationInfo.getStorageType() == FileRecord.StorageType.OptimizeStorage) {
                    if (!mIsDeleteAll) {
                        GmsDeleteResultDialog gmsDeleteResultDialog = new GmsDeleteResultDialog();
                        if (extras != null) {
                            gmsDeleteResultDialog.setTotalSize(extras.getLong(FileOperator.HANDLED_SIZE));
                        }
                        gmsDeleteResultDialog.showAllowingStateLoss(mFragment.getFragmentManager(),
                                GmsDeleteResultDialog.class.getSimpleName());
                    }
                }
            }
        }
    }

    private int getTargetChildCount(ArrayList<FileRecord> recordList) {
        int ret = 0;
        if (recordList != null && !recordList.isEmpty()) {
            for (FileRecord record : recordList) {
                ret += record.getItemCount(false);
            }
        }
        return ret;
    }

    private int getTargetChildCount(FileRecord record) {
        return record.getItemCount(false);
    }
}
